//
//  WebViewController.m
//  HealthCA_H5
//
//  Created by 创维海通 on 2017/7/6.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>

#import "JQBounceSpot1Animation.h"
#import "UpdateHtml.h"
#import "CustomProgress.h"

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
//颜色十六进制
#define RGBOF(rgbValue)     [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 \
alpha:1.0]

@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate>
{
    UIView *bgView;
}
@property (strong,nonatomic) WKWebView *webView;
@property (strong,nonatomic) CustomProgress *custompro;
@property (strong,nonatomic) UIView *customproBgView;

@property id<JQIndicatorAnimationProtocol> animation;

@property (strong,nonatomic)UpdateHtml *updata;

@property BOOL isAnimating;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initWebView];
}

#pragma mark -init
- (void)initWebView
{
    //配置环境
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
    config.mediaPlaybackRequiresUserAction = false;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    config.userContentController = [[WKUserContentController alloc] init];
//    [config.userContentController addScriptMessageHandler:self name:@"AppModel"];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.238:8085/static/hcyx/index.html"];
//    NSURL *url = [NSURL URLWithString:@"http://106.2.186.52:10000/healthca/hcyx/index.html"];
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    [self loading];
    
    //曾华桥新增
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [self.webView loadRequest:request];
    
    
//    NSString *htmlPathString=@"html/healthca/hcyx.html";
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:htmlPathString ofType:@"html"];
//    [self.webView loadFileURL:[NSURL URLWithString:@"html/healthca/hcyx/index.html" relativeToURL:[[NSBundle mainBundle] bundleURL]]];
//    NSURL *fileURL = [NSURL fileURLWithPath:@"healthca/hcyx/index.html" relativeToURL:[[NSBundle mainBundle] bundleURL]];
//   [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"healthca/hcyx/index.html" relativeToURL:[[NSBundle mainBundle] bundleURL]]]];
//    if(filePath){
//        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
//            NSURL *path = [[NSBundle mainBundle] URLForResource:@"/html/healthca/hcyx/index.html" withExtension:@""];
//            [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
//            NSString *html = [self loadHostPathURL:@"index"];
////            //加载js
//            [self.webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
            // iOS9. One year later things are OK.
//            NSURL *fileURL = [NSURL fileURLWithPath:filePath];
//            [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
//        } else {
            // iOS8. Things can be workaround-ed
            //   Brave people can do just this
            //   fileURL = try! pathForBuggyWKWebView8(fileURL)
            //   webView.loadRequest(NSURLRequest(URL: fileURL))
            
//            NSURL *fileURL = [self.fileHelper fileURLForBuggyWKWebView8:[NSURL fileURLWithPath:path]];
//            NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
//            [self.webView loadRequest:request];
//        }
//    }
    
//    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    [self readJson];
}

-(void)readJson{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"沙盒%@", paths[0]);
    _updata = [[UpdateHtml alloc] init];
    __weak typeof(&*self)wself = self;
    [_updata downFileFromServer:@"http://106.2.186.52:10000/healthca/ver.json" pro:^(double pro){
        NSLog(@"%f", pro);
        
    } success:^(NSString *path){
        NSLog(@"%@", path);
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        
        //删除版本号
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtURL:[[NSURL alloc] initFileURLWithPath:path] error:&error];
        
        NSInteger oldVersion = [[NSUserDefaults standardUserDefaults] integerForKey:@"version"]; //老的版本号
        NSInteger newVersion = [[dic objectForKey:@"version"] integerValue]; //新的版本号
        
        NSString *locationPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"healthca.zip"];
        
        if(oldVersion < newVersion){ //有新版本，或者本地没得版本，就去服务器拉取(防止被清理)
            wself.customproBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
            wself.customproBgView.backgroundColor = RGBOF(0x008FF7);
            [wself.view addSubview:wself.customproBgView];
            wself.custompro = [[CustomProgress alloc] initWithFrame:CGRectMake(10, ScreenHeight/2-40, wself.view.frame.size.width-20, 20)];
            
            wself.custompro.maxValue = 100;
            //设置背景色
            wself.custompro.bgimg.backgroundColor =[UIColor colorWithRed:188/255.0 green:188/255.0 blue:188/255.0 alpha:1];
            wself.custompro.leftimg.backgroundColor =[UIColor greenColor];
            //可以更改lab字体颜色
            wself.custompro.presentlab.textColor = [UIColor whiteColor];
            [wself.customproBgView addSubview:wself.custompro];
            
            UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2-50, ScreenHeight/2-10, 180, 25)];
            lable.text = @"版本更新中";
            [wself.customproBgView addSubview:lable];
            
            //删除旧版本
            [[NSFileManager defaultManager] removeItemAtURL:[[NSURL alloc] initFileURLWithPath:locationPath] error:&error];
            
            [wself downZip:[dic objectForKey:@"downloadLink"] version:newVersion];
        }else{
            
            NSString *locationPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"healthca.zip"];
            NSString * htmlPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"www"];
            [_updata OpenZip:locationPath unzipto:htmlPath];
            
            NSString *path = [NSTemporaryDirectory() stringByAppendingString:@"www/healthca/hcyx/index.html"];
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:path];
            [self loadUrl:fileURL];
        }
    } filed:^(NSString *msg){
        NSString *locationPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"healthca.zip"];
        if([[NSFileManager defaultManager] fileExistsAtPath:locationPath]){
            NSString * htmlPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"www"];
            [_updata OpenZip:locationPath unzipto:htmlPath];
            
            NSString *path = [NSTemporaryDirectory() stringByAppendingString:@"www/healthca/hcyx/index.html"];
            NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:path];
            [self loadUrl:fileURL];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"系统提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                
            }]];
            [wself presentViewController:alert animated:YES completion:nil];
        }
        
    }];
    
}

-(void)downZip:(NSString *)url version:(NSInteger)version{
    __weak typeof(&*self)wself = self;
    [_updata downFileFromServer:url pro:^(double pro){
        NSLog(@"%f", pro);
        dispatch_async(dispatch_get_main_queue(), ^(void){
            [wself.custompro setPresent:pro*100];
        });
    } success:^(NSString *path){
        NSLog(@"%@", path);
        [[NSUserDefaults standardUserDefaults] setInteger:version forKey:@"version"];//存起来
        NSString * htmlPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"www"];
        [_updata OpenZip:path unzipto:htmlPath];
        [wself.customproBgView removeFromSuperview];
        
        NSString *locaHtmlpath = [NSTemporaryDirectory() stringByAppendingString:@"www/healthca/hcyx/index.html"];
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:locaHtmlpath];
        [self loadUrl:fileURL];
    } filed:^(NSString *msg){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"系统提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            
        }]];
        [wself presentViewController:alert animated:YES completion:nil];
    }];
}

-(void)loading{
    
    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    bgView.backgroundColor = [UIColor grayColor];
    bgView.alpha = 0.5f;
    [self.view addSubview:bgView];
    
    UIView *loadView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth/2, ScreenHeight/2, 60, 60)];
    [bgView addSubview:loadView];
    self.animation = [[JQBounceSpot1Animation alloc] init];
    [self.animation configAnimationAtLayer:loadView.layer withTintColor:[UIColor redColor] size:CGSizeMake(60, 60)];
    self.isAnimating = YES;
}

-(void)loadUrl:(NSURL *)fileURL{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    }else{
        NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
        [self.webView loadRequest:request];
    }
}

- (NSString *)loadHostPathURL:(NSString *)url{
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    return html;
    
}

//创建tmp/www
-(void)createwww{
    if(![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@www/",NSTemporaryDirectory()]]){
        // Create "/temp/www" directory
        NSError *error;
        NSFileManager *fileManager= [NSFileManager defaultManager];
        NSURL *temDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"www"];
        [fileManager createDirectoryAtURL:temDirURL withIntermediateDirectories:YES attributes:nil error:&error];
    }
}
//将文件copy到tmp目录
- (NSURL *)fileURLForBuggyWKWebView8:(NSURL *)fileURL {
    NSError *error = nil;
    if (!fileURL.fileURL || ![fileURL checkResourceIsReachableAndReturnError:&error]) {
        return nil;
    }
    // Create "/temp/www" directory
    NSFileManager *fileManager= [NSFileManager defaultManager];
    NSURL *temDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"www"];
    [fileManager createDirectoryAtURL:temDirURL withIntermediateDirectories:YES attributes:nil error:&error];
    
    NSURL *dstURL = [temDirURL URLByAppendingPathComponent:fileURL.lastPathComponent];
    // Now copy given file to the temp directory
    [fileManager removeItemAtURL:dstURL error:&error];
    [fileManager copyItemAtURL:fileURL toURL:dstURL error:&error];
    // Files in "/temp/www" load flawlesly :)
    return dstURL;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [bgView removeFromSuperview];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [bgView removeFromSuperview];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"页面加载失败" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark -WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"AppModel"]) {
        // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
        NSLog(@"%@", message.body);
        NSDictionary *callString = message.body;
        NSString *temp1 = callString[@"body"];
        NSString *temp = [temp1 stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""];
        NSData *imageData = [[NSData alloc] initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
        UIImage *image = [UIImage imageWithData:imageData];
        [self saveImageToPhotos:image];
    }
}

- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
